import 'package:f_enjoy_plus/components/Header.dart';
import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:f_enjoy_plus/pages/repair/controller/addOrEditVM.dart';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/loading.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../utils/loadImage.dart';

class RepairAddOrEditPage extends StatelessWidget {
  RepairAddOrEditPage({super.key});
  final vm = Get.put(AddOrEditVM());

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent, // 保证空白处也能响应
      onTap: () {
        FocusScope.of(context).unfocus(); // 取消所有输入框焦点
      },
      child: Scaffold(
        appBar: Header(title: '报修'),
        body: Column(
          children: [
            Expanded(
              child: ListView(
                children: [
                  titleHeader('报修房屋'),
                  selectHouse(),
                  titleHeader('报修信息'),
                  selectRepairType(),
                  mobileRow(),
                  appointmentRow(),
                  descriptionRow(),
                  attachmentRow(),
                ],
              ),
            ),

            submitButton(),

            SizedBox(height: 16),
          ],
        ),
      ),
    );
  }
}

Widget titleHeader(String title) {
  return Padding(
    padding: EdgeInsets.all(16),
    child: Text(
      title,
      style: TextStyle(fontSize: 12, color: AppColors.textSecondary),
    ),
  );
}

void showHouseSelection(BuildContext context) {
  final vm = Get.find<AddOrEditVM>();
  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    builder: (BuildContext context) {
      return Obx(() {
        return Wrap(
          children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '请选择房屋',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: vm.houseList.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    contentPadding: EdgeInsets.symmetric(horizontal: 8),
                    titleAlignment: ListTileTitleAlignment.center,
                    title: Text(
                      vm.houseList[index]['name'],
                      textAlign: TextAlign.center,
                    ),
                    onTap: () {
                      // 处理选择房子的逻辑
                      vm.onSelectHouse(vm.houseList[index]);
                      Get.back();
                    },
                  );
                },
              ),
            ),
            Container(padding: EdgeInsets.all(16)),
          ],
        );
      });
    },
  );
}

Widget selectHouse() {
  final vm = Get.find<AddOrEditVM>();
  return Container(
    width: double.infinity,
    padding: EdgeInsets.all(16),
    color: Colors.white,
    child: GestureDetector(
      onTap: () {
        showHouseSelection(Get.context!);
      },
      child: Obx(() {
        return Row(
          children: [
            Expanded(
              child: Text(
                vm.selectedHouse['name'] ?? '请选择房屋',
                style: TextStyle(
                  color:
                      vm.selectedHouse['name'] != null
                          ? AppColors.textPrimary
                          : AppColors.textSecondary,
                ),
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: AppColors.textSecondary,
              size: 16,
            ),
          ],
        );
      }),
    ),
  );
}

void showRepairTypeSelection(BuildContext context) {
  final vm = Get.find<AddOrEditVM>();
  showModalBottomSheet(
    context: context,
    builder: (BuildContext context) {
      return Obx(() {
        return Wrap(
          children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Text(
                '请选择维修类型',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: vm.repairTypeList.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(vm.repairTypeList[index]['name']),
                    onTap: () {
                      vm.onSelectRepairType(vm.repairTypeList[index]);
                      Get.back();
                    },
                  );
                },
              ),
            ),
          ],
        );
      });
    },
  );
}

Widget selectRepairType() {
  final vm = Get.find<AddOrEditVM>();
  return Container(
    width: double.infinity,
    padding: EdgeInsets.all(16),
    color: Colors.white,
    child: GestureDetector(
      onTap: () {
        showRepairTypeSelection(Get.context!);
      },
      child: Obx(() {
        return Row(
          children: [
            SizedBox(width: 80, child: Text('维修类型')),
            Expanded(
              child: Text(
                vm.selectedRepairType['name'] ?? '请选择维修类型',
                style: TextStyle(
                  color:
                      vm.selectedRepairType['name'] != null
                          ? AppColors.textPrimary
                          : AppColors.textSecondary,
                ),
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              color: AppColors.textSecondary,
              size: 16,
            ),
          ],
        );
      }),
    ),
  );
}

Widget mobileRow() {
  final vm = Get.find<AddOrEditVM>();

  return Container(
    width: double.infinity,
    padding: EdgeInsets.all(16),
    color: Colors.white,
    child: Row(
      children: [
        SizedBox(width: 80, child: Text('手机号码')),
        Expanded(
          child: TextField(
            controller: vm.mobileController,
            decoration: InputDecoration(
              hintText: '请输入手机号码',
              hintStyle: TextStyle(
                color: AppColors.textSecondary,
                fontSize: 14,
              ),
              border: InputBorder.none,
            ),
            style: TextStyle(color: AppColors.textPrimary),
          ),
        ),
      ],
    ),
  );
}

Widget appointmentRow() {
  final vm = Get.find<AddOrEditVM>();
  return Container(
    width: double.infinity,
    padding: EdgeInsets.all(16),
    color: Colors.white,
    child: Row(
      children: [
        SizedBox(width: 80, child: Text('预约日期')),
        Expanded(
          child: GestureDetector(
            onTap: () async {
              final DateTime initialDate =
                  (vm.appointment.value != '')
                      ? DateTime.parse(vm.appointment.value)
                      : DateTime.now();
              DateTime? picked = await showDatePickerForDay(
                Get.context!,
                initialDate,
              );
              if (picked != null) {
                vm.appointment.value = picked.toString().split(' ')[0];
              }
            },
            child: Obx(() {
              return Text(
                vm.appointment.value != '' ? vm.appointment.value : '请选择预约日期',
                style: TextStyle(
                  color:
                      vm.appointment.value != ''
                          ? AppColors.textPrimary
                          : AppColors.textSecondary,
                ),
              );
            }),
          ),
        ),
      ],
    ),
  );
}

Future<DateTime?> showDatePickerForDay(
  BuildContext context,
  DateTime initialDate,
) {
  final today = DateTime.now();
  final firstDate = DateTime(today.year, today.month, today.day);
  return showDatePicker(
    context: context,
    initialDate: initialDate,
    firstDate: firstDate,
    lastDate: DateTime(today.year, today.month + 1, today.day),
    initialEntryMode: DatePickerEntryMode.calendarOnly,
    helpText: "请选择日期",
    cancelText: "取消",
    confirmText: "确定",
    initialDatePickerMode: DatePickerMode.day,
  );
}

Widget descriptionRow() {
  final vm = AddOrEditVM.to;
  return Container(
    width: double.infinity,
    padding: EdgeInsets.all(16),
    color: Colors.white,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('问题描述'),
        SizedBox(height: 8),
        TextField(
          minLines: 1,
          maxLines: null, // 自动扩展高度
          controller: vm.descriptionController,
          decoration: InputDecoration(
            hintText: '请填写报修内容，工作人员将快速帮您解决问题。',
            hintStyle: TextStyle(color: AppColors.textSecondary, fontSize: 14),
            border: UnderlineInputBorder(
              borderSide: BorderSide(color: AppColors.border, width: 0.5),
            ),
          ),
        ),
      ],
    ),
  );
}

Widget attachmentRow() {
  final vm = AddOrEditVM.to;
  return Container(
    padding: EdgeInsets.all(16),
    color: AppColors.white,
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('问题附件'),
        SizedBox(height: 8),
        Obx(() {
          int itemCount =
              vm.attachment.length < 6 ? vm.attachment.length + 1 : 6;
          return GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
            ),
            itemCount: itemCount,
            itemBuilder: (context, index) {
              if (index == vm.attachment.length && vm.attachment.length < 6) {
                // 添加按钮
                return Container(
                  decoration: BoxDecoration(color: AppColors.background),
                  child: IconButton(
                    icon: Icon(Icons.add_a_photo_outlined),
                    onPressed: () {
                      // 选择图片逻辑
                      LoadImageUtils.showImagePickerBottomSheet(
                        context: context,
                        title: '选择图片',
                        limit: 6,
                        onImageSelected: (path, dialogContext) async {
                          await vm.uploadImage(path, index);
                          // 上传完成后关闭底部弹窗
                          Navigator.pop(dialogContext);
                        },
                      );
                    },
                  ),
                );
              } else {
                // 展示图片
                return Stack(
                  children: [
                    Container(
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: AppColors.background,
                          width: 0.5,
                        ),
                      ),
                      child: Image.network(
                        vm.attachment[index]?['url'] ?? '',
                        fit: BoxFit.cover,
                        width: double.infinity,
                        height: double.infinity,
                      ),
                    ),
                    // 删除按钮
                    Positioned(
                      top: -10,
                      right: -10,
                      child: IconButton(
                        icon: Icon(
                          Icons.cancel,
                          color: AppColors.primary,
                          size: 24,
                        ),
                        onPressed: () {
                          // 删除图片逻辑
                          vm.attachment.removeAt(index);
                        },
                      ),
                    ),
                  ],
                );
              }
            },
          );
        }),
      ],
    ),
  );
}

Widget submitButton() {
  final vm = AddOrEditVM.to;
  return Container(
    height: 48,
    padding: EdgeInsets.symmetric(horizontal: 16),
    width: double.infinity,
    child: ElevatedButton(
      onPressed: () {
        vm.submit();
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.add_circle_outline, color: AppColors.white, size: 24),
          SizedBox(width: 8),
          Text('提交审核', style: TextStyle(color: AppColors.white, fontSize: 16)),
        ],
      ),
    ),
  );
}
